package com.example.demo.config;


import com.example.demo.model.User;

import com.example.demo.repository.UserRepository;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.userdetails.UserDetails;

import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.core.userdetails.UsernameNotFoundException;

import org.springframework.stereotype.Service;

import org.springframework.security.core.userdetails.User.UserBuilder;


import static org.springframework.security.core.userdetails.User.withUsername;


@Service

public class DatabaseUserDetailsService implements UserDetailsService {


    @Autowired

    private UserRepository userRepository;


    @Override

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userRepository.findByUsername(username)

                .orElseThrow(() -> new UsernameNotFoundException("User not found"));

        System.out.println("Found user in database: " + user.getUsername());
        System.out.println("Password from database: " + user.getPassword());

        UserBuilder builder = withUsername(user.getUsername());

        builder.password(user.getPassword());
        builder.roles("USER");  // 添加默认角色

        return builder.build();

    }

}